package com.helpers;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

//This example creates two PersonBeans, creates an ArrayList, adds the beans to the
//list, serializes the ArrayList to an XML file.
//It then loads from the XML file into a new ArrayList
//
//Keywords: ArrayList, Serialize, XMLEncode, XMLDecode
//Note: Change the XML file while the 10 second Thread.sleep is waiting to see that
//the data is actually loaded from the file.

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
import java.util.ArrayList;

public class PersonBeanTry {
	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return String.format("[PersonBean: name='%s', age=%d]", name, age);
	}

	public static void main(String[] args) {
		PersonBeanTry person1 = new PersonBeanTry();

		person1.setName("Joe");
		person1.setAge(30);

		PersonBeanTry person2 = new PersonBeanTry();

		person2.setName("Jane");
		person2.setAge(25);

		ArrayList arrayList1 = new ArrayList();
		arrayList1.add(person1);
		arrayList1.add(person2);

		try {
			System.out.println("List 'arrayList1' = '" + arrayList1 + "'");
			FileOutputStream outputStream = new FileOutputStream("D:\\PersonBean.xml");
			XMLEncoder encoder = new XMLEncoder(outputStream);
			encoder.writeObject(arrayList1);
			encoder.close();
			Thread.sleep(2000);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		try {
			FileInputStream inputStream = new FileInputStream("D:\\PersonBean.xml");
			XMLDecoder decoder = new XMLDecoder(inputStream);
			ArrayList<PersonBeanTry> arrayList2 = (ArrayList<PersonBeanTry>) decoder.readObject();
			decoder.close();
			System.out.println("List 'arrayList2' = '" + arrayList2 + "'");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}